package com.wzw.wx.api.tools;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
//import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
//import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
//import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Date;

/**
 * word文件转PDF
 *
 * @auth 吴泽稳 2023-03-09
 */
public class Word2PDF implements OfficeTransUtil {
    private static Logger log = LoggerFactory.getLogger(Word2PDF.class);

    public void execute(String sourcePath) {

        String targetPath = sourcePath.substring(0, sourcePath.lastIndexOf("."));
//      sourcePath =  C:\Users\WuZewen\Desktop\文档转换格式测试\test.docx
        documents4jWordToPdf(sourcePath, targetPath + new Date().getTime() + ".pdf");

    }

    public String executeInputStream(InputStream docxInputStream) throws Exception {
        File outputFile = new File(new Date().getTime() + ".pdf");
        OutputStream outputStream = new FileOutputStream(outputFile);
        IConverter converter = LocalConverter.builder().build();
        boolean execute = converter.convert(docxInputStream)
                .as(DocumentType.DOCX)
                .to(outputStream)
                .as(DocumentType.PDF).schedule().get();
//                    .execute();
        outputStream.close();
        docxInputStream.close();

        log.info("转换完毕 targetPath = {}", outputFile.getAbsolutePath());
        System.out.println("转换完毕 targetPath = " + outputFile.getAbsolutePath());
        converter.shutDown();
        return outputFile.getAbsolutePath();

    }

    /**
     * 通过documents4j 实现word转pdf
     *
     * @param sourcePath 源文件地址 如 /root/example.doc
     * @param targetPath 目标文件地址 如 /root/example.pdf
     */
    public static void documents4jWordToPdf(String sourcePath, String targetPath) {
        File inputWord = new File(sourcePath);
        File outputFile = new File(targetPath);
        try {
            InputStream docxInputStream = new FileInputStream(inputWord);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            boolean execute = converter.convert(docxInputStream)
                    .as(DocumentType.DOCX)
                    .to(outputStream)
                    .as(DocumentType.PDF).schedule().get();
//                    .execute();
            outputStream.close();
            docxInputStream.close();

            log.info("转换完毕 targetPath = {}", outputFile.getAbsolutePath());
            System.out.println("转换完毕 targetPath = " + outputFile.getAbsolutePath());
            converter.shutDown();
            return;
        } catch (Exception e) {
            log.error("[documents4J] word转pdf失败:{}", e.toString());
        }
    }


}
